package com.stardust.controller;

import com.stardust.pojo.ResultControl;
import com.stardust.pojo.User;
import com.stardust.service.UserService;
import com.stardust.viewobject.UserViewObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
@RequestMapping("User")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("test")
    @ResponseBody
    public ResultControl test(HttpServletRequest httpServletRequest){
        Object object = httpServletRequest.getSession().getAttribute("user");//利用object对象存储本次会话
        ResultControl resultControl = new ResultControl();
        resultControl.data.put("user",object);
        return resultControl;
    }

    //用户注册模块 post请求获取表单 requestboday获取注册用户信息 hander获取ip
    @RequestMapping(value = "regist",method = RequestMethod.POST)
    @ResponseBody
    public ResultControl regist(@RequestBody User user, @RequestHeader("Host") String host){
        user.setLoginIP(host);
        user.setLoginDate(new Date());

        return userService.Regist(user);
    }

    @RequestMapping(value = "login",method = RequestMethod.POST)
    @ResponseBody
    public ResultControl login(@RequestBody UserViewObject userViewObject, HttpServletRequest httpServletRequest){
        if((new ResultControl().setCode()).equals(userViewObject.getCode())){
            userViewObject.setLoginIP(httpServletRequest.getRemoteAddr());//更新登录IP
            ResultControl resultControl = userService.Login(userViewObject);//调用登录控制方法
            if (resultControl.code == ResultControl.OK){
                httpServletRequest.getSession().setAttribute("user",userViewObject);
            }
            return resultControl;
        }else {
            return new ResultControl(ResultControl.ERROR,"验证码错误");
        }
    }
}
